#include "pack_ip.h"
#include "forward_util.h"
#include "common.h"
#include <stdio.h> // NULL
#include <arpa/inet.h> // in_addr

pack_ip::pack_ip(){
	ptr = NULL;
}

pack_ip::pack_ip(void* ptr){
	this->ptr = (struct iphdr*)ptr;
}

pack_ip::~pack_ip(){

}

string pack_ip::get_saddr(){

	struct in_addr ia;
	ia.s_addr = ptr->saddr;
	string ip = inet_ntoa(ia);
	return ip;
}

string pack_ip::get_daddr(){

	struct in_addr ia;
	ia.s_addr = ptr->daddr;
	string ip = inet_ntoa(ia);
	return ip;
}

uint32_t pack_ip::get_saddr_uint(){
	return ptr->saddr;
}

uint32_t pack_ip::get_daddr_uint(){
	return ptr->daddr;
}

void pack_ip::set_saddr(const char* ip){
	ptr->saddr = inet_addr(ip);
}

void pack_ip::set_daddr(const char* ip){
	ptr->daddr = inet_addr(ip);
}

void pack_ip::set_saddr(uint32_t addr){
	ptr->saddr = addr;
}

void pack_ip::set_daddr(uint32_t addr){
	ptr->daddr = addr;
}

uint32_t pack_ip::get_head_len(){
	uint32_t ihl = (unsigned char)(ptr->ihl) * 4;
	return ihl;
}

uint32_t pack_ip::get_total_len(){
	uint32_t tot = ntohs(ptr->tot_len);
	return tot;
}

uint8_t pack_ip::get_protocol(){
	return ptr->protocol;
}

uint16_t pack_ip::get_check(){
	return ptr->check;
}

char* pack_ip::get_transfer_layer(){
	char* p = (char*)ptr + get_head_len();
	return p;
}

void pack_ip::print_buffer(){

	string saddr = get_saddr();
	string daddr = get_daddr();
	uint32_t ihl = get_head_len();
	if (ihl > 60) return;
	uint32_t tot_len = get_total_len();
	uint8_t protocol = get_protocol();
	uint16_t check = get_check();

	LOGI("[IP] saddr=%s daddr=%s headlen=%d dlen=%d protocol=%d check=%u",
			saddr.c_str(),
			daddr.c_str(),
			ihl,
			tot_len,
			protocol,
			check);

	forward_util::print_buff((char*)ptr, ihl);
}
